import 'package:catguard/global/global_data.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';

import '../../../config/config.dart';
import '../../../generated/assets.dart';
import '../../../routers/routers.dart';
import '../../../views/common_widget.dart';
import 'device_search_logic.dart';

class DeviceSearchPage extends StatefulWidget {
   DeviceSearchPage({super.key});

  @override
  State<StatefulWidget> createState() => _DeviceSearchPageState();
}

class _DeviceSearchPageState extends State<DeviceSearchPage> with SingleTickerProviderStateMixin {
  final logic = Get.find<DeviceSearchLogic>();

  late AnimationController _animationController;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 4), // 设置动画时长，时间越短播放速度越快
    );
    _animationController.repeat(); // 循环播放
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg,
      resizeToAvoidBottomInset: false,
      body: Column(
        children: [
          CommonWidget.commonAppBar("添加设备"),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(top: 30.w, left: 35.w, right: 35.w),
            padding: EdgeInsets.only(left: 35.w, right: 35.w, top: 35.w, bottom: 15.w),
            decoration: BoxDecoration(
              color: Config.colorBg2,
              borderRadius: BorderRadius.circular(Config.roundBig.w),
            ),
            child: Column(
              children: [
                Row(
                  children: [
                    Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20.w),
                        gradient: RadialGradient(
                          colors: [
                            Config.colorMain.withOpacity(0.8),
                            Config.colorBg2,
                          ],
                          center: Alignment.center, // 设置扩散中心
                          radius: 1, // 扩散半径（越大扩散范围越大）
                        ),
                      ),
                      child: Icon(
                        Icons.search_rounded,
                        size: 24.w,
                        color: Config.colorText1,
                      ),
                    ),
                    SizedBox(
                      width: 12.w,
                    ),
                    Obx(
                      () => RichText(
                        text: TextSpan(
                          text: ' ', // 文本内容
                          style: TextStyle(
                              fontSize: Config.textSizeInfo.w, color: Config.colorText3), // 基础样式
                          children: [
                            TextSpan(
                              text: logic.deviceList.isEmpty
                                  ? '正在搜索附近设备，请确保设备处于'
                                  : '发现附近设备...', // 子文本
                              style: TextStyle(
                                fontSize: Config.textSizeInfo.w,
                                color: Config.colorText2,
                              ),
                            ),
                            TextSpan(
                              text: logic.deviceList.isEmpty ? '配置网络中...' : '',
                              style: TextStyle(
                                fontSize: Config.textSizeInfo.w,
                                color: Config.colorMain,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Obx(
                  () => Visibility(
                    visible: logic.deviceList.isEmpty,
                    child: Container(
                      margin: EdgeInsets.symmetric(vertical: 50.w),
                      width: 500.w,
                      height: 500.w,
                      child: Lottie.asset(
                        controller: _animationController,
                        Assets.animLottieDeviceSearching,
                        width: 500.w,
                        height: 500.w,
                        onLoaded: (composition) {
                          _animationController.duration =
                              composition.duration ~/ 2; // 将动画加速播放（速率为2倍）
                        },
                      ),
                    ),
                  ),
                ),
                Obx(
                  () => Visibility(
                    visible: logic.deviceList.isEmpty,
                    child: Text(
                      '搜索中...',
                      style:
                          TextStyle(color: Config.colorText1, fontSize: Config.textSizeContent.w),
                    ),
                  ),
                ),
                Obx(
                  () => ListView(
                    padding: EdgeInsets.only(top: 25.w),
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    children: List.generate(logic.deviceList.length, (index) {
                      return familyItem(index, () {});
                    }),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  familyItem(int index, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        children: [
          SizedBox(
            height: 114.w,
            child: Row(
              children: [
                Container(
                  width: 68.w,
                  height: 68.w,
                  padding: EdgeInsets.all(10.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(33.w),
                    color: Config.colorMain.withOpacity(0.4),
                  ),
                  clipBehavior: Clip.antiAlias,
                  child: Image.asset(
                    Assets.imagesProduct01Mini,
                    fit: BoxFit.fitWidth,
                  ),
                ),
                SizedBox(width: 20.w),
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      logic.deviceList[index],
                      style:
                          TextStyle(color: Config.colorText1, fontSize: Config.textSizeContent.sp),
                    ),
                    SizedBox(
                      height: 5.w,
                    ),
                    Text(
                      '12:34:56:78:9A:BC',
                      style: TextStyle(color: Config.colorText3, fontSize: Config.textSizeInfo.sp),
                    ),
                  ],
                ),
                Expanded(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () {
                        global.deviceLinkState.value = 0;
                        Get.toNamed(Routes.selectWifi)?.then((value) {
                          LogUtil.v("从配网页面返回搜索页面 配网情况=${global.deviceLinkState.value}");
                          if (global.deviceLinkState.value == 2) {
                            Future.delayed(const Duration(milliseconds: 50),(){
                              Get.back();
                            });
                          } else {
                            logic.deviceList.clear();
                            logic.addSearchDevice();
                          }
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 25.w, vertical: 4),
                        decoration: BoxDecoration(
                          border: Border.all(color: Config.colorMain, width: 1.5.w),
                          borderRadius: BorderRadius.circular(Config.roundNormal.w),
                        ),
                        child: Text(
                          "添加",
                          style:
                              TextStyle(color: Config.colorMain, fontSize: Config.textSizeInfo.sp),
                        ),
                      ),
                    ),
                  ],
                ))
              ],
            ),
          ),
          Visibility(
            visible: logic.deviceList.length > 1 && index < logic.deviceList.length - 1,
            child: CommonWidget.commonDivider(),
          ),
        ],
      ),
    );
  }
}
